//
//  DropdownMenuView.m
//  PhotoScrollView
//
//  Created by 冷悦 on 16/3/19.
//  Copyright © 2016年 URANUS. All rights reserved.
//

#import "DropdownMenuView.h"
#import "DisclosureIndicatorView.h"
#import "Masonry.h"

#ifndef kDropdownMenuViewHeaderHeight
#define kDropdownMenuViewHeaderHeight 300.0f
#endif

#ifndef kDropdownMenuViewAutoHideHeight
#define kDropdownMenuViewAutoHideHeight 44.0f
#endif

@interface DropdownMenuView()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, copy)NSArray *titles;

@property (nonatomic, assign)BOOL isMenuShow;

@property (nonatomic, assign)NSUInteger selectedIndex;

@property (nonatomic, strong)UIButton *titleButton;

@property (nonatomic, strong)DisclosureIndicatorView *arrowView;

@property (nonatomic, strong)UITableView *tableView;

@property (nonatomic, strong)UIView *backgroundView;

@property (nonatomic, strong)UIView *wrapperView;

@end

@implementation DropdownMenuView

- (instancetype)initWithTitles:(NSArray *)titles{
    if (self = [super init]) {
        _width = 0.0;
        _animationDuration = 0.4;
        _backgroundAlpha = 0.3;
        _cellHeight = [UIScreen mainScreen].bounds.size.height*0.07;
        _isMenuShow = NO;
        _selectedIndex = 0;
        _titles = titles;
        
        [self addSubview:self.titleButton];
        [self addSubview:self.arrowView];
        [self.wrapperView addSubview:self.backgroundView];
        [self.wrapperView addSubview:self.tableView];
        
        // 添加KVO监听tableView的contenOffset属性，添加上滑返回功能
        NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
        [self.tableView addObserver:self forKeyPath:@"contentOffset" options:options context:nil];
    }
    
    return self;
}

- (void)didMoveToWindow
{
    [super didMoveToWindow];
    if (self.window){
        [self.window addSubview:self.wrapperView];
        [self.titleButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.top.bottom.equalTo(self);
        }];
        [self.arrowView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.titleButton.mas_right);
            make.centerY.equalTo(self.titleButton.mas_centerY);
            make.width.equalTo(self.arrowView.mas_height);
            make.height.equalTo(self.titleButton).multipliedBy(0.5);
            make.right.equalTo(self).offset(-FiveOffsetViewMargin);
        }];
        // 依附于导航栏下面
        [self.wrapperView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self);
            make.bottom.equalTo(self.window);
            make.top.equalTo(self.mas_bottom).offset(1);
        }];
        [self.backgroundView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.wrapperView);
        }];
        UIView *barView = [UIView new];
        barView.backgroundColor = LineColor222;
        [self.wrapperView addSubview:barView];
        [barView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.equalTo(self.tableView);
            make.height.mas_equalTo(1);
        }];
        CGFloat tableCellsHeight = _cellHeight * _titles.count;
        [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.wrapperView.mas_centerX);
            if (self.width > 79.99999)
            {
                make.width.mas_equalTo(self.width);
            }
            else
            {
                make.left.equalTo(self.wrapperView).offset(_tableViewOffset);
                make.right.equalTo(self.wrapperView).offset(-_tableViewOffset);
            }
            make.top.equalTo(self.wrapperView.mas_top).offset(-tableCellsHeight - kDropdownMenuViewHeaderHeight);
            make.bottom.equalTo(self.wrapperView.mas_bottom).offset(tableCellsHeight + kDropdownMenuViewHeaderHeight).priorityLow();
            make.bottom.lessThanOrEqualTo(self.window).offset(-10);
        }];
        self.wrapperView.hidden = YES;
    }
    else{
        // 避免不能销毁的问题
        [self.wrapperView removeFromSuperview];
    }
}

- (void)dealloc{
    [self.tableView removeObserver:self forKeyPath:@"contentOffset"];
}

#pragma mark - Override
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    // 遇到这些情况就直接返回
    if (!self.userInteractionEnabled || !self.isMenuShow)
        return;
    
    // 这个就算看不见也需要处理
    if ([keyPath isEqualToString:@"contentOffset"]) {
        CGPoint newOffset = [[change valueForKey:@"new"] CGPointValue];
        if (newOffset.y > kDropdownMenuViewAutoHideHeight) {
            if (_isSliderHidden == YES) {
               self.isMenuShow = !self.isMenuShow;
            }
        }
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.titles.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return self.cellHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TableViewCell" forIndexPath:indexPath];
    cell.textLabel.text = [self.titles objectAtIndex:indexPath.row];
    
    if (self.selectedIndex == indexPath.row) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    cell.tintColor = self.cellAccessoryCheckmarkColor;
    cell.backgroundColor = self.cellColor;
    cell.textLabel.font = self.textFont;
    cell.textLabel.textColor = self.textColor;
    
    return cell;
}

#pragma mark - UITableViewDataDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.selectedIndex = indexPath.row;
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.selectedAtIndex)
    {
        self.selectedAtIndex((int)indexPath.row);
    }
}

#pragma mark - Event Response
- (void)handleTapTitleButton:(UIButton *)button{
    self.isMenuShow = !self.isMenuShow;
}

- (void)showMenu {
    self.titleButton.enabled = NO;
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, kDropdownMenuViewHeaderHeight)];
    headerView.backgroundColor = self.cellColor;
    self.tableView.tableHeaderView = headerView;
    [self.tableView layoutIfNeeded];
    
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.wrapperView.mas_top).offset(-kDropdownMenuViewHeaderHeight);
        make.bottom.equalTo(self.wrapperView.mas_bottom).offset(kDropdownMenuViewHeaderHeight).priorityLow();
        make.bottom.lessThanOrEqualTo(self.window).offset(-30);
    }];
    
    self.wrapperView.hidden = NO;
    self.backgroundView.alpha = 0.0;
    
    [UIView animateWithDuration:self.animationDuration
                     animations:^{
                         self.arrowView.transform = CGAffineTransformRotate(self.arrowView.transform, M_PI);
                     }];
    
    [UIView animateWithDuration:self.animationDuration * 1.5
                          delay:0
         usingSpringWithDamping:0.7
          initialSpringVelocity:0.5
                        options:UIViewAnimationOptionCurveLinear
                     animations:^{
                         [self.tableView layoutIfNeeded];
                         self.backgroundView.alpha = self.backgroundAlpha;
                         self.titleButton.enabled = YES;
                     } completion:nil];
}

- (void)hideMenu {
    self.titleButton.enabled = NO;
    CGFloat tableCellsHeight = _cellHeight * _titles.count;
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.wrapperView.mas_top).offset(-tableCellsHeight - kDropdownMenuViewHeaderHeight);
        make.bottom.equalTo(self.wrapperView.mas_bottom).offset(tableCellsHeight + kDropdownMenuViewHeaderHeight).priorityLow();
        make.bottom.lessThanOrEqualTo(self.window).offset(-30);
    }];
    
    [UIView animateWithDuration:self.animationDuration
                     animations:^{
                         self.arrowView.transform = CGAffineTransformRotate(self.arrowView.transform, M_PI);
                     }];
    
    [UIView animateWithDuration:self.animationDuration * 1.5
                          delay:0
         usingSpringWithDamping:0.7
          initialSpringVelocity:0.5
                        options:UIViewAnimationOptionCurveLinear
                     animations:^{
                         [self.tableView layoutIfNeeded];
                         self.backgroundView.alpha = 0.0;
                     } completion:^(BOOL finished) {
                         self.wrapperView.hidden = YES;
                         [self.tableView reloadData];
                         self.titleButton.enabled = YES;
                     }];
}

#pragma mark - Public
- (void)setTitleName:(NSString *)title{
    [self.titleButton setTitle:title forState:UIControlStateNormal];
    
    for (NSString *titleString in self.titles) {
        if ([titleString isEqualToString:title]) {
            return;
        }
    }
    
    NSMutableArray *array = [NSMutableArray arrayWithArray:_titles];
    [array addObject:title];
    _titles = [array copy];
}

#pragma mark - Getters And Setters
- (UIColor *)cellColor{
    if (!_cellColor){
        _cellColor = [UIColor whiteColor];
    }
    
    return _cellColor;
}

@synthesize cellSeparatorColor = _cellSeparatorColor;
- (UIColor *)cellSeparatorColor{
    if (_cellSeparatorColor == nil) {
        _cellSeparatorColor = [UIColor colorWithRed:0.9098 green:0.9137 blue:0.9098 alpha:1.0];
    }
    
    return _cellSeparatorColor;
}

- (void)setCellSeparatorColor:(UIColor *)cellSeparatorColor {
    _cellSeparatorColor = cellSeparatorColor;
    self.tableView.separatorColor = cellSeparatorColor;
}

- (UIColor *)cellAccessoryCheckmarkColor {
    if (_cellAccessoryCheckmarkColor == nil){
        _cellAccessoryCheckmarkColor = [UIColor colorWithRed:52/255.0 green:152/255.0 blue:219/255.0 alpha:1.0];
    }
    
    return _cellAccessoryCheckmarkColor;
}

@synthesize textColor = _textColor;
- (UIColor *)textColor {
    if (_textColor == nil){
        _textColor = [UIColor whiteColor];
    }
    
    return _textColor;
}

- (void)setTextColor:(UIColor *)textColor {
    [self.titleButton setTitleColor:textColor forState:UIControlStateNormal];
    
    _textColor = textColor;
}

@synthesize textFont = _textFont;
- (UIFont *)textFont {
    if(_textFont == nil) {
        _textFont = [UIFont systemFontOfSize:17];
    }
    
    return _textFont;
}

- (void)setTextFont:(UIFont *)textFont {
    _textFont = textFont;
    [self.titleButton.titleLabel setFont:textFont];;
}

- (UIButton *)titleButton {
    if (_titleButton == nil) {
        _titleButton = [[UIButton alloc] init];
        [_titleButton setTitle:[self.titles objectAtIndex:0] forState:UIControlStateNormal];
        [_titleButton addTarget:self action:@selector(handleTapTitleButton:) forControlEvents:UIControlEventTouchUpInside];
        [_titleButton.titleLabel setFont:self.textFont];
        [_titleButton setTitleColor:self.textColor forState:UIControlStateNormal];
        _titleButton.titleLabel.textColor = [UIColor colorWithRed:0.314 green:0.608 blue:0.843 alpha:1.000];
    }
    
    return _titleButton;
}

- (DisclosureIndicatorView *)arrowView {
    if (_arrowView == nil) {
        _arrowView = [DisclosureIndicatorView new];
        _arrowView.backgroundColor = [UIColor clearColor];
        _arrowView.disclosureIndicatorWidth = 2;
        _arrowView.disclosureIndicatorEnable = YES;
        _arrowView.disclosureIndicatorColor = TextColor150;
        _arrowView.direction = Bottom;
    }
    
    return _arrowView;
}

- (UITableView *)tableView
{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        _tableView.separatorColor = self.cellSeparatorColor;
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"TableViewCell"];
    }
    
    return _tableView;
}

- (UIView *)wrapperView {
    if (_wrapperView == nil) {
        _wrapperView = [UIView new];
        _wrapperView.clipsToBounds = YES;
    }
    
    return _wrapperView;
}

- (UIView *)backgroundView
{
    if (_backgroundView == nil) {
        _backgroundView = [UIView new];
        _backgroundView.backgroundColor = [UIColor clearColor];
        _backgroundView.alpha = self.backgroundAlpha;
    }
    
    return _backgroundView;
}

- (void)setIsMenuShow:(BOOL)isMenuShow {
    if (_isMenuShow != isMenuShow) {
        _isMenuShow = isMenuShow;
        
        if (isMenuShow) {
            [self showMenu];
        } else {
            [self hideMenu];
        }
    }
}

- (void)setSelectedIndex:(NSUInteger)selectedIndex {
    if (_selectedIndex != selectedIndex) {
        _selectedIndex = selectedIndex;
        [_titleButton setTitle:[_titles objectAtIndex:selectedIndex] forState:UIControlStateNormal];
    }
    
    self.isMenuShow = NO;
}

- (void)setWidth:(CGFloat)width {
    if (width < 80.0) {
        DDLogInfo(@"width should be set larger than 80, otherwise it will be set to be equal to window width");
        
        return;
    }
    
    _width = width;
}

- (void)setTextAlignment:(NSTextAlignment)textAlignment{
    if (textAlignment == NSTextAlignmentLeft) {
        self.titleButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        self.titleButton.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    }
}

- (void)setTableViewOffset:(CGFloat)tableViewOffset{
    _tableViewOffset = tableViewOffset;
}


@end
